<!-- 收入计划 -->
<template>
  <div class="revenue-box expenditure-box">
    <!-- 编制中 -->
    <el-collapse v-model="activeNames1" v-if="type == 1">
      <el-collapse-item v-for="(item, index) in collapseData1" :key="index" :name="index">
        <template v-if="item.child" slot="title">
          <div>
            {{ item.chargeItemName + ' ' + item.planYear + ' 年 ' }}
            <span style="padding-right: 10px">年计划收入{{ item.plannedIncome | formatMoney }}元</span>
            比去年计划收入{{ GetUp(item.lastIncome) ? '增加' : '减少' }}
            <span :class="{ 'clolor-blue': GetUp(item.lastIncome), 'clolor-red': !GetUp(item.lastIncome) }">{{ item.lastIncome | formatMoney }}元</span>
            同比{{ GetUp(item.increase) ? '增加' : '减少' }}
            <span :class="{ 'clolor-blue': GetUp(item.increase), 'clolor-red': !GetUp(item.increase) }">{{ item.increase }}</span>
            比去年执行收入{{ GetUp(item.executiveIncome) ? '增加' : '减少' }}
            <span :class="{ 'clolor-blue': GetUp(item.executiveIncome), 'clolor-red': !GetUp(item.executiveIncome) }">{{ item.executiveIncome | formatMoney }}元</span>
          </div>
        </template>
        <template v-else slot="title">
          {{ item.chargeItemName }}
        </template>
        <el-table :data="item.child" style="width: 100%" border row-key="categoryGroup" default-expand-all :tree-props="{children: 'child'}">
          <el-table-column align="left" prop="chargeItemName" width="300"  class="tree-charge">
            <template slot="header"> 收费项 </template>
            <template slot-scope="scope" >
              <div @click="nameClick(scope.row)">{{ scope.row.chargeItemName }}</div>
            </template>
          </el-table-column>
          <template v-for="(col) in Columns1(item)">
            <template v-if="col.children">
              <el-table-column :label="col.label" :key="col.categoryGroup" :class-name="col.classname" :align="col.align">
                <el-table-column v-for="(col2, j) in col.children" :class-name="col2.classname" :key="j" :prop="col2.prop" :label="col2.label" :width="col2.width ? col2.width : null" :align="col2.align ? col2.align : null" :min-width="col2.minwidth ? col2.minwidth : null">
                  <template slot-scope="scope">
                    <div class="cursor-pointer" @click="cellClick(item, scope.row, col2)">{{ (col2.customRender ? col2.customRender(scope.row, scope.row[col2.prop]) : scope.row[col2.prop]) | formatMoney }}</div>
                  </template>
                </el-table-column>
              </el-table-column>
            </template>
            <template v-else>
              <el-table-column :key="col.categoryGroup" :prop="col.prop" :label="col.label" :width="col.width ? col.width : null" :align="col.align ? col.align : null" :min-width="col.minwidth ? col.minwidth : null">
                <template slot-scope="scope">
                  <div>{{ (col.customRender ? col.customRender(scope.row, scope.row[col.prop]) : scope.row[col.prop]) | formatMoney }}</div>
                </template>
              </el-table-column>
            </template>
          </template>
        </el-table>
      </el-collapse-item>
    </el-collapse>

    <!-- 执行中 -->
    <div v-if="type == 2">
      <el-collapse v-model="activeNames2">
        <el-collapse-item v-for="(item, index) in collapseData2" :key="index" :name="index">
          <template slot="title">
            <div>
              {{ item.chargeItemName + '截止 ' + item.planYear + ' 年 ' + item.planMonth + ' 月，年累计执行' }}{{ item.cumulativeExecution | formatMoney }} {{ '元，' + item.belowPlan }}
              <span :class="{ 'clolor-blue': GetUp(item.belowPlanPercentage), 'clolor-red': !GetUp(item.belowPlanPercentage) }">({{ item.belowPlanPercentage }})</span>
              {{ '预测全年收入' }}{{ item.calculateAmount | formatMoney }}{{ '元，' + item.higherThanPlanned }}
              <span :class="{ 'clolor-blue': GetUp(item.plannedPercentage), 'clolor-red': !GetUp(item.plannedPercentage) }">({{ item.plannedPercentage }})</span>
            </div>
          </template>
          <el-table :data="item.child" border row-key="categoryGroup" default-expand-all :tree-props="{children: 'child'}">
            <el-table-column align="center" prop="chargeItemName" width="300">
              <template slot="header">
                
              </template>
              <template slot-scope="scope">
                <div @click="nameClick(scope.row, item)">{{ scope.row.chargeItemName }}</div>
              </template>
            </el-table-column>
            <template v-for="(col) in Columns2(item)">
              <template v-if="col.children">
                <el-table-column :label="col.label" :key="col.categoryGroup" :class-name="col.classname" :align="col.align">
                  <el-table-column v-for="(col2) in col.children" :class-name="col2.classname" :key="col2.categoryGroup" :prop="col2.prop" :label="col2.label" :width="col2.width ? col2.width : null" :align="col2.align ? col2.align : null" :min-width="col2.minwidth ? col2.minwidth : null">
                    <template slot-scope="scope">
                      <div class="cursor-pointer" @click="cellClick(item, scope.row, col2)">{{ (col2.customRender ? col2.customRender(scope.row, scope.row[col2.prop]) : scope.row[col2.prop]) | formatMoney }}</div>
                    </template>
                  </el-table-column>
                </el-table-column>
              </template>
              <template v-else>
                <el-table-column :key="col.categoryGroup" :prop="col.prop" :label="col.label" :width="col.width ? col.width : null" :align="col.align ? col.align : null" :min-width="col.minwidth ? col.minwidth : null">
                  <template slot-scope="scope">
                    <div v-if="col.prop == 'PlannedPercentage'">{{ col.customRender ? col.customRender(scope.row, scope.row[col.prop]) : scope.row[col.prop] }}</div>
                    <div v-else>{{ (col.customRender ? col.customRender(scope.row, scope.row[col.prop]) : scope.row[col.prop]) | formatMoney }}</div>
                  </template>
                </el-table-column>
              </template>
            </template>
          </el-table>
        </el-collapse-item>
      </el-collapse>
    </div>
    <historicalPlan v-if="showHistoricalPlan"  @close-dialog="closeDialog" :name="typeName" :type.sync="typeNumber" :assetCode="assetCode"></historicalPlan>
    <el-dialog :title="title" :visible="showCommodityIncome" width="65%" :before-close="closeDialog" :close-on-click-modal="false">
      <buildingDialog ref="formDialog" :isEdit='isEdit' :errorMessage="errorMessage" v-if="showBuilding" :buildingData="dialogData" @FormVerify="FormVerify"></buildingDialog>
      <parkingDialog ref="formDialog" :isEdit='isEdit' :errorMessage="errorMessage" v-if="showParking" :parkingData="dialogData" @FormVerify="FormVerify"></parkingDialog>
      <unEquipment ref="formDialog" :isEdit='isEdit' :errorMessage="errorMessage" v-if="showUnEquipment" :unEquipmentData="dialogData" @FormVerify="FormVerify"></unEquipment>
      <largeAdvertising ref="formDialog" :isEdit='isEdit' :errorMessage="errorMessage" v-if="showAdvert" :largeAdData="dialogData" @FormVerify="FormVerify"></largeAdvertising>
      <monthlyEstimate ref="formDialog" :isEdit='isEdit' :errorMessage="errorMessage" v-if="showMonth" :monthData="dialogData" @FormVerify="FormVerify"></monthlyEstimate>
    </el-dialog>
  </div>
</template>
<script>
import buildingDialog from './components/dialogIncome/buildingDialog.vue'
import parkingDialog from './components/dialogIncome/parkingDialog.vue'
import unEquipment from './components/dialogIncome/unEquipment.vue'
import largeAdvertising from './components/dialogIncome/largeAdvertising.vue'
import monthlyEstimate from './components/dialogIncome/monthlyEstimate.vue'
import historicalPlan from '../planTab/components/historicalPlan.vue';
import Api from '../../api/incomeAndExpenditurePlan';
export default {
  components: { historicalPlan ,buildingDialog,parkingDialog,unEquipment,largeAdvertising,monthlyEstimate},
  data() {
    return {
      dialogData:{},
      showBuilding:false,
      showParking:false,
      showUnEquipment:false,
      showAdvert:false,
      showMonth:false,
      showCommodityIncome: false,
      type: this.$route.query.type ? this.$route.query.type : 1,
      showHistoricalPlan: false,
      value: 'zichan',
      options: [
        {
          value: 'zichan',
          label: '资产',
        },
      ],
      activeNames1: [],
      activeNames2: [],
      collapseData1: [],
      compileIncomePlanData: null, //编制中，收入
      compileSpendingPlanData: null, //编制中，支出
      collapseData2: [],
      title: '',
      month: null,
      planKey: null,
      configverify: {
        resultMessage: null,
        vilidateResult: true,
      },
      typeName: '',
      typeNumber: 1,
      assetCode:'',
      errorMessage:{
        success:true,
        resultMessage:''
      },
      isEdit:''
    };
  },
  computed: {
    Columns1() {
      return function (item) {
        let align = 'center';
        let width = null;
        let columns = [
          {
            label: '计划收入',
            prop: 'plannedIncome',
            align: align,
            width: '180',
          },
          {
            label: '上一财年收入',
            prop: 'preYearExeforecastIncome',
            align: align,
            width: '180',
          },
        ];
        let isXjl = item.chargeItemName.indexOf('现金流') > -1; // 是否现金流
        for (let i = 0; i < 12; i++) {
          let obj = {
            align: align,
            label: (this.planDetail.planYear ? this.planDetail.planYear : '') + '年' + (i + 1) + '月收入',
            classname: this.month == i + 1 ? 'active' : '',
            children: [],
          };
          if (!isXjl) {
            //现金流 不展示权责
            obj.children.push({
              label: '权责',
              month: i + 1,
              classname: this.month == i + 1 ? 'active' : '',
              prop: 'monthMap',
              customRender: (row, text) => {
                if (text) {
                  return text[i + 1] ? text[i + 1].forecastIncome : '-';
                }
                return '';
              },
              align: align,
              width: isXjl ? '180' : '180', //不展示权责时宽度为160
            });
          }
          obj.children.push({
            label: '现金流',
            month: i + 1,
            prop: 'monthMap',
            customRender: (row, text) => {
              if (text) {
                return text[i + 1] ? text[i + 1].cashIncome : '-';
              }
              return '';
            },
            align: align,
            width: isXjl ? '180' : '180',
          });

          columns.push(obj);
        }

        return columns;
      };
    },
    Columns2() {
      return function (item) {
        let align = 'center';
        let width = null;
        let columns = [
          {
            label: '计划全年收入',
            prop: 'currYearCalculateAmount',
            align: align,
            width: '180',
          },
          {
            label: '预测全年收入',
            prop: 'forecastIncome',
            align: align,
            width: '180',
          },
          {
            label: '偏差度',
            prop: 'plannedPercentage',
            align: align,
            width: '100',
          },
        ];
        let strkey = 'forecastIncome';
        if (item.chargeItemName.indexOf('现金流') > -1) {
          strkey = 'cashIncome';
          columns.push(
            {
              label: '累计执行收入',
              prop: 'cumulativeExecution',
              align: align,
              width: '180',
            },
            {
              label: '累计欠费金额',
              prop: 'accumulatedArrears',
              align: align,
              width: '180',
            },
          );
        }
        let children1 = [];
        let children2 = [];
        let m = parseInt(item.planMonth) - 1;
        for (let i = 1; i <= m; i++) {
          children1.push({
            label: i + '月',
            month: i,
            classname: this.month == i ? 'active' : 'bk-grey',
            prop: 'monthMap',
            customRender: (row, text) => {
              if (text) {
                return text[i] ? text[i][strkey] : '-';
              }
              return '';
            },
            align: align,
            width: '180',
          });
        }
        for (let i = m + 1; i <= 12; i++) {
          children2.push({
            label: i + '月',
            month: i,
            classname: this.month == i ? 'active' : '',
            prop: 'monthMap',
            customRender: (row, text) => {
              if (text) {
                return text[i] ? text[i][strkey] : '-';
              }
              return '';
            },
            align: align,
            width: '180',
          });
        }
        if(children1&&children1.length>0){
          columns.push({
            align: align,
            label: '实际执行收入',
            children: children1,
          })
        }
        if(children2&&children2.length>0){
          columns.push({
            align: align,
            label: '预测收入',
            children: children2,
          })
        }

        return columns;
      };
    },
    planDetail() {
      return this.$store.state.planDetail;
    },
  },
  //监控data中的数据变化
  watch: {
    planDetail: {
      // immediate: true,
      // deep: false,
      handler(plandetail) {
        if (plandetail) {
          this.month = plandetail.month;
          this.GetData();
        }
      },
    },
  },
  filters: {
    formatMoney(s, type) {
      if (s == null || s == undefined) return '-';
      s = s.toString();
      let negative = false;
      // è´Ÿæ•°
      if (s.slice(0, 1) === '-') {
        negative = true;
        s = s.slice(1);
      }
      if (s.slice(0, 1) === '+') {
        s = s.slice(1);
      }
      if (/[^0-9\.]/.test(s)) return '0';
      if (s == null || s == '') return '0';
      s = s.toString().replace(/^(\d*)$/, '$1.');
      s = (s + '00').replace(/(\d*\.\d\d)\d*/, '$1');
      s = s.replace('.', ',');
      var re = /(\d)(\d{3},)/;
      while (re.test(s)) s = s.replace(re, '$1,$2');
      s = s.replace(/,(\d\d)$/, '.$1');
      if (type == 0) {
        // ä¸å¸¦å°æ•°ä½(é»˜è®¤æ˜¯æœ‰å°æ•°ä½)
        var a = s.split('.');
        if (a[1] == '00') {
          s = a[0];
        }
      }
      return `¥${negative ? '-' : ''}${s}`;
    },
  },
  mounted() {
  },
  methods: {
    GetUp(str) {
      if (!str) return false;
      if (str.indexOf('+') > -1) return true;
      return false;
    },
    GetData() {
      this.planKey = this.$route.query.planKey;
      if (this.type == 1) {
        Api['toCompileIncomePlan']({
          planKey:this.planKey,
          itemType:3,
          statusList:[1,2,4]
        }).then(res => {
          if (res && res.success) {
            this.collapseData1 = res.rows
          }
        });
      } else {
        Api['toPerformIncomePlan']({
          planKey: this.planKey,
          itemType:3,
          statusList:[1,2,4]
        }).then(res => {
          if (res && res.success) {
            res.rows.forEach((ele,index)=>{
              ele.id=ele.categoryGroup
            })
            this.collapseData2 = res.rows;
          }
        });
      }
    },
    nameClick(row, item) {
      //之前type==2才能弹窗，现在都不弹了
      if (this.type == 3 && (row.chargeItemCategory==2||row.chargeItemCategory==3)) {
        this.showHistoricalPlan = true;
        this.typeName = row.chargeItemName;
        this.assetCode = row.assetCode
        return;
      }
    },
    cellClick(item, row, col2) {
      if(row.chargeItemCategory==2||row.chargeItemCategory==3){
        this.title = '详细信息';
        this.assetCode = row.assetCode
        let data = {
          assetKey:row.assetKey,
          assetCode:row.assetCode,
          billConfigKey: row.monthMap[col2.month].billConfigKey, // row.billConfigKey,
          chargeItemType:row.chargeItemType,
          planKey:this.$route.query.planKey
        };
        this.isEdit = row.isEdit
        if(row.chargeItemType==0){
          return
        }
        Api.income(data).then(res => {
          this.dialogData = res
          this.showCommodityIncome = true;
          if (row.chargeItemType == '1') {
            //商铺 写字楼
            this.showBuilding = true
            setTimeout(() => {
              this.$refs.formDialog.init()
            }, 100);
          }  else if (row.chargeItemType == '2') {
            this.showParking = true
            setTimeout(() => {
              this.$refs.formDialog.init()
            }, 100);
          } else if (row.chargeItemType == '3') {
            //停车场
            this.showAdvert = true
            setTimeout(() => {
              this.$refs.formDialog.init()
            }, 100);
          } else if (row.chargeItemType == '4') {
            //广告
            this.showUnEquipment = true
            setTimeout(() => {
              this.$refs.formDialog.init()
            }, 100);
          } else if (row.chargeItemType == '5') {
            //活动 其他
            let strkey = 'forecastIncome';
            if (item.chargeItemName.indexOf('现金流') > -1) {
              strkey = 'cashIncome';
            }
            let list = []
            for (let i in row.monthMap) {
              list.push({
                month:i,
                paymentAmount: row.monthMap[i][strkey]
              })
            }
            this.showMonth = true
            setTimeout(() => {
              this.$refs.formDialog.init(list)
            }, 100);
          }  else {
            return;
          }
        });
      }
    },
    FormVerify(data) {
      data.planKey = this.$route.query.planKey;
      data.assetCode = this.assetCode
      Api.configverify(data).then(res => {
        if (res.success) {
          this.configverify = res;
          if (res.vilidateResult) {
            this.Ok(data);
          } else {
            this.errorMessage = res
            this.$message.warning('校验失败');
          }
        }
      });
    },
    Ok(data) {
      Api.create(data).then(res => {
        this.closeDialog()
        this.showCommodityIncome = false;
        this.$message.success(res.message);
        this.GetData();
      });
    },
    closeDialog() {
      if(this.$refs.formDialog)
      this.$refs.formDialog.closeDialog()
      setTimeout(() => {
        this.showHistoricalPlan = false;
        this.showBuilding=false
        this.showParking=false
        this.showUnEquipment=false
        this.showAdvert=false
        this.showMonth = false
        this.showCommodityIncome = false;
      }, 100);
    },
  },
};
</script>
<style lang='scss'>

.revenue-box {
  padding: 30px;
  .btn-submit {
    position: fixed;
    top: 14px;
    right: 310px;
    z-index: 9999;
  }
  .active {
    background: #eff5ff !important;
  }
  .bk-grey {
    background: #f5f7fa;
  }
  .clolor-red {
    color: #ff0000;
    padding-right: 10px;
  }
  .clolor-blue {
    color: #29c37f;
    padding-right: 10px;
  }
  .m_title {
    margin-bottom: 10px;
    font-size: 16px;
    font-weight: bold;
  }
  ::v-deep .el-dialog {
    min-height: 400px;
    .el-dialog__header {
      background: #444;
    }
  }
  .title2 {
    display: flex;
    justify-content: flex-start;
  }
  
}
</style>